package com.yitiao.consumer;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class DefaultMessageListener implements MessageListener {

//    @Resource
//    private Map<String, MessageHandler> messageHandlerMap;

    @Override
    public void onMessage(Message message) {
        MessageProperties messageProperties = message.getMessageProperties();
        String exchange = messageProperties.getReceivedExchange();
        String routingKey = messageProperties.getReceivedRoutingKey();
        String queueName = messageProperties.getConsumerQueue();
        String key = StrUtil.format("{},{},{}", exchange, routingKey, queueName);
        Map<String, MessageHandler> messageHandlerMap = SpringUtil.getBean("messageHandlerMap");
        MessageHandler messageHandler = messageHandlerMap.get(key);
        if (ObjectUtil.isNotNull(messageHandler)) {
            messageHandler.handleMessage(message);
        } else {
            log.info("message handler not found.[{}]",message.getMessageProperties().toString());
        }
    }
}
